#!/usr/bin/env python
import os
import sys
from cgi import parse_qs, FieldStorage
import logging
import requests

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

logger.addHandler(handler)

CONTENT_TYPE = os.environ.get('CONTENT_TYPE')
REQUEST_METHOD = os.environ.get('REQUEST_METHOD')

if REQUEST_METHOD == 'POST' and CONTENT_TYPE.startswith('application/json'):
    request_body = sys.stdin.read()

    #params = parse_qs(request_body)
    
    logger.debug('request body{}'.format(request_body))

    file_name = eval(request_body)["file_name"]
    logger.debug('file_name name{}'.format(file_name))

    if file_name:
        file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), file_name))

        if os.path.isfile(file_path):
            try:
                os.remove(file_path)
                print("Status: 200 OK")
                print("Content-Type: text/plain")
                print("")
                print("File %s has been deleted." % file_name.encode('utf-8'))
            except Exception as e:
                print("Status: 500 Internal Server Error")
                print("Content-Type: text/plain")
                print("")
                print("Failed to delete file: %s" % str(e).encode('utf-8'))
        else:
            print("Status: 404 Not Found")
            print("Content-Type: text/plain")
            print("")
            print("File %s not found." % file_name.encode('utf-8'))
    else:
        print("Status: 400 Bad Request")
        print("Content-Type: text/plain")
        print("")
        print("No file name was provided in the request.")

else:
    print("Status: 405 Method Not Allowed")
    print("Content-Type: text/plain")
    print("")
    print("This script only accepts POST requests with urlencoded form data.")

sys.stdout.flush()
